<?php

declare(strict_types=1);

namespace app\common\service\crm;

use app\common\dao\crm\ContractProductDao;
use app\common\service\hrm\FilesService;
use app\common\traits\ServiceTrait;
use app\common\dao\crm\ContractDao;
use think\facade\Db;
use app\common\validate\crm\Contract as ContractValidate;

/**
 * 合同表 服务业务层(Service)
 * @author 吕玉冰
 * @date  2022-07-23
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class ContractService
{
    protected $dao = null;

    public function __construct()
    {
        $this->dao = new ContractDao();
        $this->CPdao = new ContractProductDao();
    }

    use ServiceTrait;


    public function _list_where($data)
    {
        $where = [];
        if (isset($data['customer_id']) && !empty($data['customer_id'])) {
            $where[] = ['customer_id', '=', $data['customer_id']];
        }
        $data['where'] = $where;
        return [
            'where' => isset($data['where']) ? $data['where'] : [],
            'order' => isset($data['order']) ? $data['order'] : [],
            'field' => isset($data['field']) ? $data['field'] : ['*'],
        ];
    }

    /**
     * lvyubing
     */
    public function saveItems($data)
    {

        foreach ($data['items'] as $k => $v) {
            $itemdata = [];
            $itemdata["contract_id"] = $data["id"];
            $itemdata["product_id"] = $v["id"];
            $itemdata["num"] = $v["num"];
            $itemdata["price"] = $v["price"];
            if (!empty($itemdata["product_id"])) {
                $this->CPdao->add($itemdata);
            }
        }
    }

    public function _format(&$data)
    {
        $data['items'] = [];
        foreach ($data as $key => $value) {
            $v = explode("_", $key);
            if (is_numeric(end($v))) {
                if (!empty($value)) {
                    $data['items'][end($v)][prev($v)] = $value;
                }
                unset($data[$key]);
            }
        }
        $data['money'] = 0;
        foreach ($data['items'] as $key => $value) {
            $data['money'] += $value["num"] * $value["price"];
        }
    }

    /**
     * 保存表单数据
     * @param $data
     * @return array
     */
    public function saveForm($data)
    {
        if (empty($data)) {
            return _err(1002);
        }
        $this->_format($data);

        if (isset($data['id']) && !empty($data['id'])) {
            $validate = new ContractValidate();
            if (!$validate->scene("edit")->check($data)) {
                return _err($validate->getError());
            }
            $result = $this->dao->update($data['id'], $data);
            $where = [];
            $where[] = ["contract_id", "=", $data['id']];
            $this->CPdao->deleteByWhere($where);
            $this->saveItems($data);
            if (isset($data['files_id'])) {
                (new FilesService())->add([
                    'table_name' => 'crm_contract',
                    'table_id' => $data['id'],
                    'files_id' => $data['files_id']
                ]);
            }
            if ($result) {
                return _ok(1021);
            }
        } else {
            $validate = new ContractValidate();
            if (!$validate->scene("add")->check($data)) {
                return _err($validate->getError());
            }
            $result = $this->dao->add($data);
            if ($result) {
                $return = _ok(1023);
                if (!empty($result->id)) {
                    $return['data'] = $result->id;
                    $data['id'] = $result->id;
                    $this->saveItems($data);
                    if (isset($data['files_id'])) {
                        (new FilesService())->add([
                            'table_name' => 'crm_contract',
                            'table_id' => $result->id,
                            'files_id' => $data['files_id']
                        ]);

                    }

                }
                return $return;
            }
        }
        return _err(1005);
    }
}
    